// Proxy server that adds CORS headers to proxied request const gateway = "https://cors.jerrod.workers.dev"; // ? is used a parameter before the request URL const baseUrl = "?" + "https://demo.docusign.net/restapi/v2.1/accounts"; const authUrl = "?" + "https://account-d.docusign.com/oauth/token"; const urlEndpoint = "?" + "https://demo.docusign.net/restapi/v2.1/accounts/17140816/envelopes"; // docusignsystemdemos@mailinator.com Account Details var username = "steven@cooke.app"; const accountId = "17140816"; const jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIzZTdlYjJjMi01NmI1LTRhNzctYmM4ZS04ZGU2ZGFkZThjOGUiLCJzdWIiOiJkNWUzZjM2MC1mNmYwLTQ4OWQtYTQyNi0yMmM1NzZjZGMwY2UiLCJleHAiOiIxOTA0NTY5OTA4IiwiYXVkIjoiYWNjb3VudC1kLmRvY3VzaWduLmNvbSIsInNjb3BlIjoic2lnbmF0dXJlIGV4dGVuZGVkIGltcGVyc29uYXRpb24ifQ.kmax7iZFP4m_8N2KUupdHtdVJM0t1DWnQhY9cCNlbwCFbH9pZRydbSdNdoP8nwLbe3Sz8qtBdGOF3ZCo9pdHNSgWPjalmHYJaKarEWuZIla-TWrSFW4fzaL1XPnX-3ImpeR1sTuyH5tJnvdBO432aSenhCfQmbxE4bM8PFEfIa1uff4jNvYAlSucygC62q9MQp5RSPE9C7kUgYsGkHHrLSiStgOpoGvitbArx_qGEDkaHZj4ytHZBslnMumP7w8u96ap4PAFvMO_Suxz_dkXjyFW7nClQDr_X8Up_UkmQgj5Hbhpfst1fVEVxOm3M6xZTrvNjqfVj1wzv5CQpfhaxw"; let requestHeader; // Parent URL Used to build redirects var currentUrl = window.location.href; // API call for creating the DocuSign envelope function createEnvelope() { var phonevalid = "start"; var phone = document.getElementById("phone").value; phone = phone.replace(/\)/g, ''); phone = phone.replace(/\(/g, ''); phone = phone.replace(/\s/g, ''); phone = phone.replace(/-/g, ''); var pattern = new RegExp("^[0-9]{10}$"); phonevalid = pattern.test(phone); console.log(phonevalid); if (phonevalid) { document.getElementById("spinner").style.display = "block"; var embedded = true; fetch( // Construct URL and then build request body pathJoin([gateway, urlEndpoint]), { method: "POST", headers: requestHeader, body: JSON.stringify({ emailSubject: "Part 11 Embedded Signing via SMS", emailBlurb: "Please let us know if you have any questions.", status: "sent", documents: [{ documentId: "1", name: "Document Name", documentBase64: document.getElementById("inputBase64Doc").value, fileExtension: "docx" }], recipients: { signers: [{ tabs: { signHereTabs: [{ tabLabel: "CustomerSignature", value: "default", anchorString: "\\s1\\", scaleValue: "0.7", anchorXOffset: "-15", anchorYOffset: "12", anchorHorizontalAlignment: "Right", anchorIgnoreIfNotPresent: "true", }, ], dateSignedTabs: [{ tabLabel: "CustomerDateSigned", anchorString: "$d1$", anchorXOffset: "-20", anchorYOffset: "0", anchorHorizontalAlignment: "Right", anchorIgnoreIfNotPresent: "true", }, ], titleTabs: [{ tabLabel: "CustomerTitle", anchorString: "$t1$", anchorXOffset: "-20", anchorYOffset: "-2", width: "40", anchorHorizontalAlignment: "Right", anchorIgnoreIfNotPresent: "true", }, ], fullnameTabs: [{ tabLabel: "CustomerName", value: "default", anchorString: "$n1$", anchorXOffset: "-20", anchorYOffset: "0", anchorHorizontalAlignment: "Right", anchorIgnoreIfNotPresent: "true", }, ], }, name: document.getElementById("name").value, email: document.getElementById("email").value, recipientId: "1", routingOrder: "1", clientUserId: document.getElementById("clientUserId").value, identityVerification: { workflowId: "261bc49f-d949-46b0-80bb-22cb9b53b652", inputOptions: [{ name: "phone_number_list", valueType: "PhoneNumberList", phoneNumberList: [{ Number: phone, CountryCode: "1" }] }] } }], }, }), } ) .then(function(response) { if (!response.ok) { throw Error(response.statusText); } else return response.json(); }) .then(function(data) { if (embedded) { createEmbedded(data); } else { let redirectUrl = new URL("status.html", currentUrl).href; window.top.location.replace(redirectUrl + "?eid=" + data.envelopeId + "&event=sent"); } }) .catch(function(error) { console.log("Request failure: ", error); alert("Request failure: ", error); }); } else { toggleCanvas(); alert("Please input a valid phone number"); } } function toggleCanvas() { $("#offcanvasTop").offcanvas("show"); } var myOffcanvas = document.getElementById('offcanvasTop') myOffcanvas.addEventListener('shown.bs.offcanvas', function () { document.getElementById("phone").focus(); }) //load status page function loadStatusPage() { var urlParams = new URLSearchParams(window.location.search); const envId = urlParams.get("eid"); const signerEvent = urlParams.get("event"); document.getElementById("signerStatement").innerHTML = "Envelope " + envId + ": " + signerEvent; if (signerEvent == "sent") { document.getElementById('actionButton').innerHTML = 'View Status ' document.getElementById("changebuttonText").innerHTML = "Change Status button to Document button"; } } // API call for generating embedded signing view function createEmbedded(responseData) { storeStyle(); let returnUrl = new URL("redirect.html", currentUrl).href; // let returnUrl = new URL("redirect.html", currentUrl).href; let requestBody = { userName: document.getElementById("name").value, email: document.getElementById("email").value, recipientId: "1", clientUserId: document.getElementById("clientUserId").value, authenticationMethod: "HTTPBasicAuth", returnUrl: returnUrl + "?eid=" + responseData.envelopeId } fetch( pathJoin([gateway, baseUrl, accountId, "envelopes", responseData.envelopeId, "views", "recipient"]), { method: "POST", headers: requestHeader, body: JSON.stringify(requestBody) } ) .then(function(response) { if (!response.ok) { throw Error(response.statusText); } return response.json(); }) .then(function(data) { // Redirect to embedded signing URL document.getElementById("signingFrame").setAttribute("src", data.url); var signingSession = new bootstrap.Modal(document.getElementById('myModal'), { keyboard: true, focus: true, show: true, backdrop: 'static' }); signingSession.show(); }) .then(function(myJson) { console.log(myJson); }) .catch(function(error) { console.log("Request failure: ", error); alert("Request failure: ", error); }); } //modal redirect page function function redirect() { currentUrl = window.location.href; console.log(currentUrl); var urlParams = new URLSearchParams(window.location.search); const envId = urlParams.get("eid"); const signerEvent = urlParams.get("event"); let redirectUrl = new URL("status.html", currentUrl).href; console.log(redirectUrl); window.top.location.replace(redirectUrl + "?eid=" + envId + "&event=" + signerEvent); } // Utility function since JS doesn't have a good way to construct URLs function pathJoin(parts, sep) { const separator = sep || '/'; parts = parts.map((part, index) => { if (index) { part = part.replace(new RegExp('^' + separator), ''); } if (index !== parts.length - 1) { part = part.replace(new RegExp(separator + '$'), ''); } return part; }) return parts.join(separator); } // JWT Access Token async function getAccessToken() { let authParams = new URLSearchParams({ assertion: jwt, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', }) let accessUrl = pathJoin([gateway, authUrl]) + "?" + authParams; let response = await fetch(accessUrl, { method: "POST", }); let responseData = await response.json(); // console.log(responseData.access_token); return responseData.access_token; } getAccessToken().then(accessToken => { requestHeader = new Headers({ "Content-Type": "application/json", "Authorization": "Bearer " + accessToken }) }); function renameButton() { document.getElementById("actionButton").innerHTML = "" + document.getElementById("buttonName").value + " "; } function toggleStatusDoc() { var container = document.getElementById("actionButton"); if (container.textContent.includes('Status')) { // Check if current displayed document.getElementById("actionButton").innerHTML = "View Document "; document.getElementById("changebuttonText").innerHTML = "Change Document button to Status button"; } else { document.getElementById("actionButton").innerHTML = "View Status "; document.getElementById("changebuttonText").innerHTML = "Change Status button to Document button"; } } function hideButton() { if (document.getElementById("buttonContainerheader").classList.contains("d-none")) { // Check if current displayed document.getElementById("buttonContainerheader").classList.remove("d-none"); } else { document.getElementById("buttonContainerheader").classList.add("d-none"); } } function displayandstoreImage() { frame.src = URL.createObjectURL(event.target.files[0]); var file = event.target.files[0] var imagefile = URL.createObjectURL(event.target.files[0]); console.log(imagefile); console.log(file); document.getElementById("frame").classList.remove("d-none"); var mimeType = file.type; // Encode the file using the FileReader API const reader = new FileReader(); reader.onloadend = () => { // Use a regex to remove data url part const base64String = reader.result .replace('data:', '') .replace(/^.+,/, ''); console.log(base64String); localStorage.setItem("image", base64String); localStorage.setItem("mimeType", mimeType); }; reader.readAsDataURL(file); document.getElementById("initialPortal").classList.add("d-none"); } function storeStyle() { var btn = document.getElementById("buttonContainer").style; console.log(btn); var btnTop = btn.getPropertyValue("top"); console.log(btnTop); var btnLeft = btn.getPropertyValue("left"); console.log(btnLeft); var el = document.getElementById("testingbutton"); localStorage.setItem("btnTop", btnTop); localStorage.setItem("btnLeft", btnLeft); var newval = localStorage.getItem("btnTop") console.log(newval); } function restartDemo() { const currentUrl = window.location.href; const startUrl = new URL("index.html", currentUrl).href; window.location.replace(startUrl); } //get signed pdf function sentButton() { document.getElementById("spinner").style.display = "block"; var urlParams = new URLSearchParams(window.location.search); const envId = urlParams.get("eid"); var dType = "combined"; fetch( pathJoin([gateway, baseUrl, accountId, "envelopes", envId, "documents/combined"]), { method: "GET", headers: requestHeader, } ) .then(res => res.blob()) .then(blob => { var file = window.URL.createObjectURL(blob); document.getElementById("signingFrame").setAttribute("src", file); var signingSession = new bootstrap.Modal(document.getElementById('myModal'), { keyboard: true, focus: true, show: true, backdrop: 'static' }); // document.getElementById("modal-header").classList.remove("d-none"); // document.getElementById("modal-footer").classList.remove("d-none"); signingSession.show(); document.getElementById("spinner").style.display = "none"; }); } var handleFileSelect = function(evt) { evt.stopPropagation(); evt.preventDefault(); var files = evt.target.files; var file = files[0]; if (files && file) { var reader = new FileReader(); reader.onload = function(readerEvt) { var binaryString = readerEvt.target.result; document.getElementById("inputBase64Doc").value = btoa(binaryString); }; reader.readAsBinaryString(file); } }; if (window.File && window.FileReader && window.FileList && window.Blob) { document.getElementById('filePicker') .addEventListener('change', handleFileSelect, false); } else { alert('The File APIs are not fully supported in this browser.'); }